<?php
namespace Modules\Activity\Http\Controllers\Client\Jika;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\Jika\Sku;
use \Modules\Activity\Entities\Jika\SwapRecord;
// use \Modules\Activity\Entities\Jika\Order;
// use \Modules\User\Entities\User;

use Validator;
use ThrowException;
use Auth;
use DB;

// 参与活动的用户（is_lucker_user）
class SkuController extends Controller
{
    // 兑换礼品
    public function swap(Request $req)
    {
        $rule = [
            'sku_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        Auth::limitTimeBeforeProcess($user, 'jika_swap', 2);

    	$sku = Sku::getEntity([
            'id' => $req->sku_id
        ]);

        $activity = $sku->activity ?: ThrowException::Conflict('活动不存在~');
        $task = $sku->task ?: ThrowException::Conflict('活动不存在~');

        // 是否超出限兑
        $task->checkSwapLimit($user) ?: ThrowException::Conflict('此任务每人仅可兑' . $task->swap_limit . '次~');

        // 活动已下架
        if (!$activity->isOnStock() || $activity->union_status !== 'working') {
            ThrowException::Conflict('活动已下架~');
        }

        // 奖品库存不足
        if ($sku->stock <= 0) {
            ThrowException::Conflict('奖品库存已兑完了~');
        }

        DB::beginTransaction();

        // 增加销量
        $sku->addSales(1) ?: ThrowException::Conflict('库存不足~');
        $activity->addSales(1, false) ?: ThrowException::Conflict('库存不足~');
        $task->addSales(1, false) ?: ThrowException::Conflict('库存不足~');

        // 扣除卡片
        $chips = $sku->task->getChipList();

        // 扣除碎片
        foreach ($chips as $chip) {
            $user->chipAsset($chip->id)->out(1, [
                'description' => '兑换扣除'
            ]) ?: ThrowException::Conflict('卡片不足~');
        }

        // 生成物品
        $package = $sku->sendAsPackageSku($user);

        // 增加记录
        $swapRecord = SwapRecord::createWith($user, $sku);


        DB::commit();

        return [
            'id' => $package->id,
            'uuid' => $package->uuid
        ];
    }

}
